package com.ms.auction.auth.oauth2.service;

import com.google.common.collect.Lists;
import com.ms.auction.auth.system.entity.TbPermission;
import com.ms.auction.auth.system.entity.TbUser;
import com.ms.auction.auth.system.service.ITbPermissionService;
import com.ms.auction.auth.system.service.ITbUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


@Slf4j
@Service
public abstract class AbstractUserDetailService implements UserDetailsService {

    @Autowired
    protected ITbUserService tbUserService;

    @Autowired
    protected ITbPermissionService tbPermissionService;


    protected abstract TbUser getUser(String var1);
    /**
     * 自定义手机号查找
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUser tbUser =getUser(username);
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if (tbUser != null) {
            // 获取用户授权
            List<TbPermission> tbPermissions = tbPermissionService.selectByUserId(tbUser.getId());
            // 声明用户授权,默认授权增加角色
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
            grantedAuthorities.add(grantedAuthority);

        /*    tbPermissions.forEach(tbPermission -> {
                if (tbPermission != null && tbPermission.getEnname() != null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
                    grantedAuthorities.add(grantedAuthority);
                }
            });*/
        }
        return new User(tbUser.getUsername(), tbUser.getPassword(), grantedAuthorities);
    }


}
